<template>
  <div>
    <Form :label-width="100" ref="formInline" :model="formInline">
      <div v-if="switchFlag">
        <Row :gutter="16" class="query-form2" >
          <i-col span="8">
            <FormItem label="二级集团：" prop="twolevelOrgName">
              <two-level-org org-code v-model="formInline.createOrgId" ></two-level-org>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="企业名称：">
              <company-select v-model="formInline.orgName"></company-select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
              <Button @click="switchQuery(false)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
            </div>
          </i-col>
        </Row>
      </div>
      <div v-else>
        <Row :gutter="16" class="query-form2" >
          <i-col span="8">
            <FormItem label="二级集团：" prop="twolevelOrgName">
              <two-level-org org-code v-model="formInline.twolevelOrgName" ></two-level-org>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="企业名称：">
              <company-select v-model="formInline.orgName"></company-select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="投入年份：">
              <DatePicker v-model="formInline.inputYear"  type="year" placeholder="请选择投入年份" style="width: 100%"></DatePicker>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16" class="query-form2" >
          <i-col span="24">
            <div style="float: right;">
              <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
              <Button @click="switchQuery(true)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
            </div>
          </i-col>
        </Row>
      </div>
    </Form>
    <Row type="flex" justify="start" class="query-form">
      <i-col>
        <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportExcel">导出</Button>
      </i-col>
    </Row>
    <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
           :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small" show-summary sum-text="合计" :summary-method="handleSummary"></Table>
    <div ref="container" style="width:100%;height:500px;"></div>
    <Modal v-model="modal1" width="800" :mask-closable="false" title="安全生产费用投入台账详情">
      <div :style="{height: divHeight, overflowY: 'auto', overflowX: 'hidden'}">
        <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="项目：" prop="codingName">
                <Input v-model="formData.codingName" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="一月（万元）：" prop="codingName">
                <Input v-model="formData.january" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.januaryDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="二月（万元）：" prop="codingName">
                <Input v-model="formData.february" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.februaryDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="三月（万元）：" prop="codingName">
                <Input v-model="formData.march" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.marchDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="四月（万元）：" prop="codingName">
                <Input v-model="formData.april" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.aprilDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="五月（万元）：" prop="codingName">
                <Input v-model="formData.may" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.mayDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="六月（万元）：" prop="codingName">
                <Input v-model="formData.june" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.juneDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="七月（万元）：" prop="codingName">
                <Input v-model="formData.july" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.julyDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="八月（万元）：" prop="codingName">
                <Input v-model="formData.august" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.augustDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="九月（万元）：" prop="codingName">
                <Input v-model="formData.september" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.septemberDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="十月（万元）：" prop="codingName">
                <Input v-model="formData.october" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.octoberDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="十一月（万元）：" prop="codingName">
                <Input v-model="formData.november" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.novemberDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="十二月（万元）：" prop="codingName">
                <Input v-model="formData.december" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="描述：">
                <Input v-model="formData.decemberDescription" type="textarea" readonly/>
              </FormItem>
            </i-col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="modal1 = false" class="ivu-btn-save" >关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {sessionStorage} from '@/common/cacheUtils.js';
import {Api} from '../../../api'
import orgDom from "@/components/input-org.vue";
import echarts from 'echarts';

export default {
  name: "safetyProductionCount",
  components:{
    orgDom,
  },
  data(){
    return {
      switchFlag: true,
      userInfo: sessionStorage('userId').getObject('userId'),
      loading: false,
      formInline: {},
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
          key: 'index',
          fixed: 'left',
        },
        {
          title: '项目',
          align: 'center',
          key: 'codingName',
          fixed: 'left',
          minWidth: 230,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '12px'
                },
                on: {
                  click: () => {
                    this.formData = JSON.parse(JSON.stringify(params.row));
                    this.modal1 = true;
                  }
                }
              }, params.row.codingName),
            ]);
          }
        },
        {
          title: '1月（万元）',
          align: 'center',
          key: 'january',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'januaryDescription',
          minWidth: 180,
        },
        {
          title: '2月（万元）',
          align: 'center',
          key: 'february',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'februaryDescription',
          minWidth: 180,
        },
        {
          title: '3月（万元）',
          align: 'center',
          key: 'march',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'marchDescription',
          minWidth: 180,
        },
        {
          title: '4月（万元）',
          align: 'center',
          key: 'april',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'aprilDescription',
          minWidth: 180,
        },
        {
          title: '5月（万元）',
          align: 'center',
          key: 'may',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'mayDescription',
          minWidth: 180,
        },
        {
          title: '6月（万元）',
          align: 'center',
          key: 'june',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'juneDescription',
          minWidth: 180,
        },
        {
          title: '7月（万元）',
          align: 'center',
          key: 'july',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'julyDescription',
          minWidth: 180,
        },
        {
          title: '8月（万元）',
          align: 'center',
          key: 'august',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'augustDescription',
          minWidth: 180,
        },
        {
          title: '9月（万元）',
          align: 'center',
          key: 'september',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'septemberDescription',
          minWidth: 180,
        },
        {
          title: '10月（万元）',
          align: 'center',
          key: 'october',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'octoberDescription',
          minWidth: 180,
        },
        {
          title: '11月（万元）',
          align: 'center',
          key: 'november',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'novemberDescription',
          minWidth: 180,
        },
        {
          title: '12月（万元）',
          align: 'center',
          key: 'december',
          minWidth: 120,
        },
        {
          title: '描述',
          align: 'center',
          key: 'decemberDescription',
          minWidth: 180,
        },
        {
          title: '合计',
          width: 80,
          align: 'center',
          fixed: 'right',
          key: 'total',
          render:(h,params)=>{
            let newpar = parseFloat(params.row.total);
            return h('div',[
              h('span', newpar)
            ]);
          }
        },
      ],
      tableHeight: '',
      infos: [],
      formData: {},
      modal1: false,
      divHeight: '',
      ruleCustom: []
    }
  },
  mounted(){
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.formInline.orgName = this.userInfo.companyName;
    this.formInline.inputYear = new Date();
    this.divHeight = window.innerHeight - 150 +'px';
    setTimeout(() => {
      this.$refs.orgDom.setCurrentOrg();
    }, 300);
    this.query();
  },
  methods: {
    query(){
      let data = {
        orgId: this.userInfo.companyId,
        orgName: this.userInfo.companyName,
      };
      this.loading = true;
      this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
      data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
      this.$http.get(Api.safetyProduction , {
        params: data
      }).then(function(res){
        this.infos = res.data.data.data;
        this.loadChart();
        this.loading = false;
      }, function(res){
        this.$Message.error('请求失败');
      });
    },
    cancel(){
      this.formInline = {
        orgName: this.userInfo.companyName,
        orgId: this.userInfo.companyId,
        inputYear: new Date()
      }
      setTimeout(() => {
        this.$refs.orgDom.setCurrentOrg();
      }, 300);
      this.query();
    },
    loadChart(){
      let container = echarts.init(this.$refs.container);
      let option = this.getOption();
      let series = [];
      this.infos.map((i)=>{
        option.legend.data.push(i.codingName);
        let arr = {
          name: i.codingName,
          type: 'bar',
          stack: 'total',
          label: {
            show: true
          },
          emphasis: {
            focus: 'series'
          },
          data: [Number(i.january), Number(i.february), Number(i.march), Number(i.april), Number(i.may), Number(i.june), Number(i.july),
            Number(i.august), Number(i.september), Number(i.october), Number(i.november), Number(i.december)]
        }
        series.push(arr);

      })
      option.series = series;
      container.setOption(option);

    },
    setOrgName(data){
      this.formInline.orgId = data.orgId;
      this.formInline.orgName = data.orgName;
    },
    exportExcel(){
      let data = {
        orgId: this.userInfo.companyId,
        orgName: this.userInfo.companyName,
      };
      this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
      data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
      this.$http.get(Api.safetyProduction + '/excel',{
        params: data,
        responseType: 'arraybuffer'
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        })
        aLink.href = URL.createObjectURL(blob);
        aLink.download = "安全生产费用投入台账.xlsx" //标题
        aLink.click();
        document.body.appendChild(aLink);
      }, function(res){
        this.$Message.error('生成失败');
      })
    },
    handleSummary ({ columns, data }) {
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: '总价'
          };
          return;
        }
        const values = data.map(item => Number(item[key]));
        if (!values.every(value => isNaN(value))) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[key] = {
            key,
            value: v.toFixed(6)
          };
        } else {
          sums[key] = {
            key,
            value: ''
          };
        }
      });

      return sums;
    },
    getOption(){
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show: false,
          data: [],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        color: ['#f44336', '#00e5ff', '#e040fb',  '#64dd17',  '#ffeb3b'  ,'#39a2ff' , '#ff9800', '#ea80fc', '#2962ff',  '#e91e63' , '#26c6da',  '#ffab91'],
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        },
        series: []
      }

      return option;
    },
    switchQuery(flag){
      this.switchFlag = flag;
      if(!this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      }else{
        this.tableHeight = this.tableHeight + 44;
      }
    },
  }
}
</script>

<style scoped>

</style>
